package com.asiainfo.iov.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asiainfo.iov.entity.MessageInfo;
import com.framework.utils.CollectionUtil;
import com.framework.utils.Y;
import com.framework2.baseEvent.BaseOnClickListener;
import com.framework2.customLoading.LoadingFooter;
import com.framework2.customLoading.indicators.BallSpinFadeLoaderIndicator;
import com.library.adapter_recyclerview.HorizontalDividerItemDecoration;
import com.library.adapter_recyclerview.UniversalAdapter;
import com.library.pulltorefresh.BaseAbstractPullToRefreshLayout;
import com.library.pulltorefresh.classical.SoftClassicalPullToRefreshLayout;
import com.library.pulltorefresh.pullableview.PullableRecyclerView;
import com.yaxin.yyt.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息中心--验证消息
 *
 * @author YobertJomi
 * className Fragment_notifyMessage
 * created at  2017/3/16  15:39
 */
public class Fragment_notifyMessage extends Fragment implements PullableRecyclerView.OnAutoLoadListener {
    private Context mContext;
    private View view;// infalte的布局
    private LinearLayout containerLayout;// 新建容器
    ////////////////////////////////
    private SoftClassicalPullToRefreshLayout refreshLayout;
    private PullableRecyclerView recyclerView;
    private UniversalAdapter adapter;
    private List<MessageInfo> infoList;
    private LoadingFooter footerView;
    private boolean requestSuccess;
    private int page = 1;
    private int pageSize = 30;
    private BaseOnClickListener onClickListener = new BaseOnClickListener() {
        @Override
        public void onBaseClick(View v) {
            MessageInfo info = (MessageInfo) v.getTag(R.id.notifyMessageTag);
//            if (null != info && info.getStatus() == 0) {
//                Intent intent = new Intent(mContext, AuthorizationDialogActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString("id", "yaya");
//                intent.putExtras(bundle);
//                startActivity(intent);
//                ((Activity) mContext).overridePendingTransition(R.anim.slide_alpha_in,
//                        R.anim.slide_alpha_out);
//            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        if (null == view) {
            containerLayout = new LinearLayout(mContext);
            view = inflater.inflate(R.layout.fragment_message, null);
            view.setMinimumHeight(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getHeight());
            view.setMinimumWidth(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getWidth());
            containerLayout.addView(view);
        } else {
            containerLayout.removeAllViews();
            containerLayout = new LinearLayout(getActivity());
            containerLayout.addView(view);
        }
        initView();
        initData();
        if (requestSuccess) {
//            requestNotifyMessageList();
        }
        return containerLayout;
    }

    private void initView() {
        recyclerView = (PullableRecyclerView) view.findViewById(R.id.recyclerView);
        refreshLayout = (SoftClassicalPullToRefreshLayout) view.findViewById(R.id.refresh_view);
    }

    private void initData() {
        initRecyclerView();
    }

    private View initFooter() {
        footerView = new LoadingFooter(mContext);
        footerView.setLoadingHint("加载更多");
        footerView.setNoMoreHint("到底了");
        footerView.setNoNetWorkHint("网络不给力啊，点击再试一次吧");
        footerView.setState(LoadingFooter.State.Loading);
        footerView.setProgressStyle(BallSpinFadeLoaderIndicator.class);
        return footerView;
    }

    @SuppressWarnings("unchecked")
    private void initRecyclerView() {
        recyclerView.setHasFixedSize(true);
        recyclerView.setCanPullDown(true);
        recyclerView.setCanPullUp(false);
        recyclerView.setHasMoreData(false);
        recyclerView.setOnAutoLoadListener(this);
        refreshLayout.setRefreshContentTextView("验证消息");
        refreshLayout.setLoadContentTextView("验证消息");
        refreshLayout.setEmptyTxt("验证消息为空,点击刷新");
        refreshLayout.setOnRefreshListener(new BaseAbstractPullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件刷新完毕了哦！
//                        pullToRefreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
//                        requestNotifyMessageList();
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }

            @Override
            public void onLoadMore(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 加载操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件加载完毕了哦！
                        pullToRefreshLayout.loadmoreFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }
        });
        //第一种，简单的颜色，高度,水平分割线
        HorizontalDividerItemDecoration horizontalDividerItemDecoration = new HorizontalDividerItemDecoration
                (getActivity());
        horizontalDividerItemDecoration.setColor(getActivity(), R.color.gray);
        horizontalDividerItemDecoration.setDividerHeightPx(1);
        recyclerView.addItemDecoration(horizontalDividerItemDecoration);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        infoList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            MessageInfo info = new MessageInfo();
            info.setId(String.valueOf(i));
            info.setTitle("我是邀请人:" + i);
            info.setContent("我是店铺:" + i);
            info.setDate("我是日期:" + i);
            info.setStatus(i > 2 ? 0 : i);
            info.setId("007" + i);
            info.setImgUrl("http://com." + i);
            infoList.add(info);
        }
        Y.y("-------------::" + infoList.size());
        if (CollectionUtil.getInstance().isEmpty(infoList)) {
            refreshLayout.showEmptyView();
        }
        adapter = initAdapter(adapter);
        recyclerView.setAdapter(adapter);
    }

    /**
     * @param adapter adapter
     * @return UniversalAdapter
     */
    @SuppressWarnings("unchecked")
    private UniversalAdapter initAdapter(UniversalAdapter adapter) {
        if (adapter == null) {
            adapter = new UniversalAdapter<MessageInfo>(getActivity(), R.layout.listitem_notifymessage, infoList) {
                @Override
                protected void getItemView(UniversalViewHolder viewHolder, final MessageInfo info, int position) {
                    viewHolder.setText(R.id.tv_title, info.getTitle());
                    viewHolder.setText(R.id.tv_content, info.getContent());
                    final TextView textView = viewHolder.getView(R.id.tv_status);
                    textView.setTag(R.id.notifyMessageTag, info);
                    int status = info.getStatus();
                    if (status == 1) {//同意
                        textView.setText("已同意");
                        textView.setBackgroundDrawable(null);
                        textView.setTextColor(getResources().getColor(R.color.trans));
                        textView.setEnabled(true);
                        textView.clearFocus();
                        textView.setClickable(false);
                    } else if (status == 2) {//拒绝
                        textView.setText("已拒绝");
                        textView.setBackgroundDrawable(null);
                        textView.setTextColor(getResources().getColor(R.color.trans));
                        textView.setEnabled(true);
                        textView.clearFocus();
                        textView.setClickable(false);
                    } else {
                        textView.setText("处理验证");
                        textView.setBackgroundResource(R.drawable.shape_blue_stroke_10px);
                        textView.setTextColor(getResources().getColor(R.color._blue));
                        textView.setClickable(true);
                        textView.setEnabled(true);
                        textView.requestFocus();
                        textView.setOnClickListener(onClickListener);
                    }
                }
            };
        }
        return adapter;
    }

//    private void requestNotifyMessageList() {
//        CustomLoadingDialogUtils.showProcessDialog(mContext, "通知消息");
//        HttpUtil.getInstance().requestShopMessageList((BaseActivity) mContext, InterfaceConfig.shopMessageList, page,
//                pageSize, new HttpUtil.OnRequestListResult<MessageInfo>() {
//            @Override
//            public void onSuccess(List<MessageInfo> list, String... msg) {
//                requestSuccess = true;
//                refreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
//                recyclerView.setOnLoading(false);
//                CustomLoadingDialogUtils.dismissProcessDialog();
//                if (!CollectionUtil.getInstance().isEmpty(list)) {
//                    if (page == 1) {
//                        infoList.clear();
//                    }
//                    infoList.addAll(list);
//                    adapter.notifyDataSetChanged();
//                } else if (CollectionUtil.getInstance().isEmpty(infoList)) {
//                    page = 1;
//                    refreshLayout.showEmptyView();
//                }
//                try {
//                    String totalCount = msg[0];
//                    int totalCount_ = Integer.parseInt(totalCount);
//                    recyclerView.setHasMoreData(page * pageSize < totalCount_);
//                    if (page * pageSize >= totalCount_) {
//                        if (footerView != null) {
//                            footerView.setState(LoadingFooter.State.NoMore);
//                        }
//                    } else {
//                        if (adapter.getFooterCount() <= 0) {
//                            adapter.addFooterViewAfterSetAdapter(initFooter());
//                        }
//                        page++;
//                    }
//                } catch (Exception e) {
//                    recyclerView.setHasMoreData(false);
//                    if (footerView != null) {
//                        footerView.setState(LoadingFooter.State.NoMore);
//                    }
//                }
//            }
//
//            @Override
//            public void onFail(int code, String msg) {
//                refreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.FAIL);
//                recyclerView.setOnLoading(false);
//                CustomLoadingDialogUtils.dismissProcessDialog();
//                ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "获取通知消息失败" : msg);
//            }
//        });
//    }

    @Override
    public void onAutoLoad(final PullableRecyclerView pullableRecyclerView) {
        pullableRecyclerView.setOnLoading(true);
//        new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                requestNotifyMessageList();
//            }
//        }.sendEmptyMessageDelayed(0, 100);
    }
}
